package com.jgraph.pad.persistence;

import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Properties;

import javax.imageio.ImageIO;

import com.jgraph.editor.persistence.JGraphPersistenceManagerFactory;
import com.jgraph.editor.persistence.JGraphPersistenceManagerFactoryMethod;
import com.jgraph.pad.util.JGraphpadImageEncoder;

/**
 * This class defines a persistence manager that handles (reads/writes)
 * {@link Image}s in several file formats.
 *
 * @author svetoslavganov@mail.utexas.edu
 * 
 */
public class JGraphpadImagePersistenceManager
        extends JGraphpadAbstractPersistenceManager<Image> {

	/**
	 * All supported file types by this persistence manager.
	 */
    public static final String[] SUPPORTED_FILE_TYPES =
    	ImageIO.getReaderFormatNames();

	@Override
	public Image readObject(String uri) throws MalformedURLException,
			IOException {
		String extension = 
			JGraphPersistenceManagerFactory.getFileExtension(uri);
		// We do not support reading of GIF for now
		if (extension.equals("gif")) {
			return null;
		}
		InputStream in = getInputStream(uri);
		return ImageIO.read(in);
	}

	@Override
	public void writeObject(Image image, String uri)
			throws MalformedURLException, IOException {
		String extension = 
			JGraphPersistenceManagerFactory.getFileExtension(uri);
		OutputStream out = getOutputStream(uri);
		if (extension.equals("gif")) {
			JGraphpadImageEncoder.writeGIF(image, out);	
		} else {
			if (image instanceof RenderedImage) {
			    ImageIO.write((RenderedImage) image, extension, out);
			}
		}
		out.flush();
		out.close();
	}


	/**
	 * Factory method for {@link JGraphpadImagePersistenceManager}s.
	 */
	public static class FactoryMethod
        extends JGraphPersistenceManagerFactoryMethod<Image> {

        public FactoryMethod(Properties properties) {
	        super(SUPPORTED_FILE_TYPES, properties);
        }

        public JGraphpadAbstractPersistenceManager<Image>
                createPersistenceManager(Properties properties) {
	         return new JGraphpadImagePersistenceManager();
        }
    }
}
